<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2024/1/16
 * Time: 10:50
 */

namespace app\service;
use app\model\admin\Keyword AS model;
use app\model\admin\Config AS config;

class Keyword
{
    private $phone = 0;
    private $computer = 0;
    public function save(string $keyword) : string{
        $find = model::where('keyword',$keyword)->find();
        $data = [
            'start_time' => $this->last_month(),
            'end_time' => date('Y-m-d'),
        ];
        if (empty($find->keyword)){
            $find = model::create(array_merge(
                [
                    'keyword' => $keyword
                ],
                $data
            ));
        }else{
            $find->save($data);
        }
        $result = $this->search($keyword);
        if (!empty($result)) {
            $baidu = $result['baidu'];
            $zhanzhanggongju = $result['zhanzhanggongju'];
            $baiduyingxiao = $result['baiduyingxiao'] ?? [];
            // $baiduyingxiao = [];
            if(!empty($baiduyingxiao)){
                $data['baiduyingxiao_json'] = json_encode($baiduyingxiao['data']);
                $data['baiduyingxiao_click'] = $baiduyingxiao['click'];
                $data['baiduyingxiao_guiding_price'] = $baiduyingxiao['guiding_price'];
                $data['baiduyingxiao_all'] = $baiduyingxiao['all'];
                $data['baiduyingxiao_type'] = $baiduyingxiao['competition'];
                $data['baiduyingxiao_showreasons'] = $baiduyingxiao['show_reasons'];
                if (!empty($baiduyingxiao['keywords']))$data['keywords'] = json_encode($baiduyingxiao['keywords']);
                $number = 1;
                if ($data['baiduyingxiao_type'] == 1)$number = 5;
                if ($data['baiduyingxiao_type'] == 2)$number = 3;
//                dd($data);
                $price = ceil($data['baiduyingxiao_click'] * $data['baiduyingxiao_guiding_price'] * 12 * $number / 100) * 100;
                $data['baiduyingxiao_price'] = $price;
                $find->save($data);
            }
//            $keywords = $zhanzhanggongju['keyword'] ?? [];
            //百度词条排序保存
//            $baidu['wordlist'] = json_decode(json_encode($result['wordlist']), true);
//            usort($baidu['wordlist'], function ($a, $b) {
//                return $b['pv'] - $a['pv']; // 倒序排列，所以使用减号
//            });
//            $keywords = array_column($baidu['wordlist'], 'word');
            if (empty($zhanzhanggongju['all'])) $zhanzhanggongju['all'] = 0;
            if (!is_numeric($zhanzhanggongju['all'])) $zhanzhanggongju['all'] = 0;
            if (empty($zhanzhanggongju['pc'])) $zhanzhanggongju['pc'] = 0;
            if (!is_numeric($zhanzhanggongju['pc'])) $zhanzhanggongju['pc'] = 0;
            if (empty($zhanzhanggongju['phone'])) $zhanzhanggongju['phone'] = 0;
            if (!is_numeric($zhanzhanggongju['phone'])) $zhanzhanggongju['phone'] = 0;
//            foreach ($keywords AS $key => $value) {
//                if (strpos($value, $keyword) === false) unset($keywords[$key]);
//            }
//
//            if (count($keywords) > 10) {
//                foreach ($keywords AS $key => $value) {
//                    $array[] = $value;
//                    if (count($array) >= 10) break;
//                }
//                $keywords = $array;
//            }
            $data = [
                'res_data' => $result,
                'zz_all' => (int)$zhanzhanggongju['pc'] + (int)$zhanzhanggongju['phone'],
                'zz_pc' => $zhanzhanggongju['pc'],
                'zz_phone' => $zhanzhanggongju['phone'],
                'all' => $baidu['number']->all->avg ?? 0,
                'pc' => $baidu['number']->pc->avg ?? 0,
                'phone' => $baidu['number']->wise->avg ?? 0,
//                'keywords' => implode(',', $keywords)
            ];
            $pc_min_price = config::get_value('pc_min_price');
            $all_min_price = config::get_value('all_min_price');
            $phone_min_price = config::get_value('phone_min_price');
            //第一版算法
//            $data['pc_price'] = floor(ceil(($data['pc'] + 100) * (100 / $this->length($keyword))/100) * 100);
//            $data['phone_price'] = floor(ceil(($data['phone'] + 100) * (100 / $this->length($keyword)/100)) * 100);
//            $data['price'] = floor(ceil((0.8 * ($data['pc_price'] + $data['phone_price']))/100)*100);
            //第二版算法
//            $a = $this->pcphone($data['pc']);
//            $b = $this->pcphone($data['phone']);
//            $data['pc_price'] = bcmul(($data['pc'] + 100)  , $a,2);
//            $data['phone_price'] = bcmul(($data['phone'] + 100) , $b,2);
//            $data['price'] = floor(ceil((0.8 * ($data['pc_price'] + $data['phone_price']))/100)*100);
            //第三版算法
            $all = $data['all'] > $data['zz_all'] ? $data['all'] : $data['zz_all'];
            $a = $this->pcphone($all);
            $data['zz_price'] = $data['price'] = ceil(bcmul(($all + 100), 1.3 * $a / 100, 0)) * 100;
            //两个价格取平均数
//            if(!empty($price)){
//                $data['price'] = bcmul($price + $data['price'],0.5,2);
//                $data['price'] = floor(ceil($data['price']*100)/100);
//            }
            //两个价格对比用最大的
            if(!empty($price)){
                if($price > $data['price'])
                    $data['price'] = $price;
            }
            $data['pc_price'] = floor(ceil($data['price'] * 0.5 / 100) * 100);
            $data['phone_price'] = floor(ceil($data['price'] * 0.6 / 100) * 100);

            $data['pc_price'] < $pc_min_price && $data['pc_price'] = $pc_min_price;
            $data['phone_price'] < $phone_min_price && $data['phone_price'] = $phone_min_price;
            $data['price'] < $all_min_price && $data['price'] = $all_min_price;
            $find->save($data);
            return 'OK';
        }else{
            return 'NO';
        }
    }

    public function pcphone($a){
        switch ($a){
            case $a == 0:
                $b = 20;
                break;
            case $a >= 1 && $a < 100:
                $b = 25;
                break;
            case $a >= 100 && $a < 200:
                $b = 27;
                break;
            case $a >= 200 && $a < 300:
                $b = 30;
                break;
            case $a >= 300 && $a < 500:
                $b = 33;
                break;
            case $a >= 500;
                $b = 33;
                break;
            default:
                $b = 33;
                break;
        }
        return $b;
    }

    public function search(string $keyword){
        try{
//            $cookie = config::get_value('baidu_cookie');
//            $cipherText = config::get_value('Cipher-Text');
            $keywords = new \app\service\Keyword();
//            $baidu =  $keywords->baidu($keyword,$cookie,$cipherText);
            $cookie = config::get_value('zhanzhanggongju_cookie');
            $zhanzhanggongju =  $keywords->zhanzhanggongju($keyword,$cookie);
            $cookie = config::get_value('baiduyingxiao_cookie');
            $reqid = config::get_value('baiduyingxiao_reqid');
            $user_id = config::get_value('baiduyingxiao_userid');
            $token = config::get_value('baiduyingxiao_token');
            $baiduyingxiao = $keywords->baiduyingxiao($keyword, $cookie, $reqid, $user_id, $token);
            return [
                'baidu' => $baidu ?? [],
                'baiduyingxiao' => $baiduyingxiao ?? [],
                'zhanzhanggongju' => $zhanzhanggongju
            ];
        }catch (\Exception $e){
            return [
                'baidu' => (object)[
                    'all' => (object)['avg' => 0],
                    'pc' => (object)['avg' => 0],
                    'wise' => (object)['avg' => 0],
                ],
                'zhanzhanggongju' => $zhanzhanggongju ?? [],
                'baiduyingxiao' => $baiduyingxiao ?? []
            ];
        }
    }

    public function baiduyingxiao(string $keyword,string $cookie,string $reqid,string $user_id,string $token){
//        dd($cookie);
        $string = $keyword;
        //$cookie = 'BIDUPSID=3517137B8AC6D0E653E94803FABA280A; PSTM=1644458657; BAIDUID=EFFA0CBA5FA8C4A12F0AAF92205891CC:SL=0:NR=10:FG=1; MCITY=-%3A; H_WISE_SIDS=40301_40080; H_WISE_SIDS_BFESS=40301_40080; BAIDUID_BFESS=EFFA0CBA5FA8C4A12F0AAF92205891CC:SL=0:NR=10:FG=1; __bid_n=18f896c03fd11528fdd6bd; H_PS_PSSID=60273_60327_60338_60297_60345; ZFY=PT6Hbe6ntNjx1y0zqXYckdzLOx1PGVZKcgkd5Eg:AwRM:C; BA_HECTOR=ah01218h84850g8k008h24ah1fv6o71j6vqqm1u; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; PSINO=5; delPer=0; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BCLID=11198394564427775115; BCLID_BFESS=11198394564427775115; BDSFRCVID=TtFOJexroG3KXsQtHd54UZVnXQpWxY5TDYrELPfiaimDVu-VYhk3EG0Pts1-dEu-S2EwogKKKgOTHI8F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; BDSFRCVID_BFESS=TtFOJexroG3KXsQtHd54UZVnXQpWxY5TDYrELPfiaimDVu-VYhk3EG0Pts1-dEu-S2EwogKKKgOTHI8F_2uxOjjg8UtVJeC6EG0Ptf8g0M5; H_BDCLCKID_SF=tRAOoC8-fIvEDRbN2KTD-tFO5eT22-usQTnl2hcHMPoosIOoWbbG5MkOjHOPXq5XyN6j--nwJxbUotoHXh3tMt_thtOp-CrpyCbWoh5TtUJMqIDzbMohqqJXQqJyKMniWKv9-pnYfpQrh459XP68bTkA5bjZKxtq3mkjbPbDfn028DKu-n5jHjjBDNDe3H; H_BDCLCKID_SF_BFESS=tRAOoC8-fIvEDRbN2KTD-tFO5eT22-usQTnl2hcHMPoosIOoWbbG5MkOjHOPXq5XyN6j--nwJxbUotoHXh3tMt_thtOp-CrpyCbWoh5TtUJMqIDzbMohqqJXQqJyKMniWKv9-pnYfpQrh459XP68bTkA5bjZKxtq3mkjbPbDfn028DKu-n5jHjjBDNDe3H; SIGNIN_UC=70a2711cf1d3d9b1a82d2f87d633bd8a04686241344RqEvnKQmNXRYPi9ev1ZAggccHaJ2uUX1MAf8ZVt9f6Ai58ziNY4BSSOZxOziFC14ZMpa49aSU997j46EfOx8QATTdd7mQzduCvm6yrdJuo4gpfL6B%2Fe4wGP13IkekT%2F5YveftUXQ7jfz4%2BwEX%2BBfDCRhTM6k1qPrH%2BVviKjgoMz1ZGDL9We4NW91M%2B1jEgHXiQECA5z12b1ZKVeaH6Aa1ogTiMHkSMnp%2B%2BwDhrpkT4Y3cAlWfxPTuYq8bv0LLP50IjANFE1b%2Bj%2Fno9Uoymqk%2BpPrd0gruWl3n6Fkzw4Z2tI4B151YnN8zFAu2nzrxu7c37948080902597497864250775237666; uc_login_unique=ab87c00ac645ec1663f54992ca0f139e; uc_recom_mark=cmVjb21tYXJrXzUwNzYzODU2; ab_sr=1.0.1_MmQyYWE4NzJhY2ZlNmRkZDlmZmU1ZmMzMDdmODMxNDJkMTU1MDgwZWQzZWI2N2JmZDRiNTdlMTE0YzgwNjE5MjU1NmU3NTI1NjMzOGVjZWQ5YjBhN2U4YTkwZjBhYzc3NmU1YzY4NmIzMGRiZDE2ZTlmODhjZDNkZmY2NDlmNTliYTE2ZTlkMmVkNTc5ZWRmMDRjZTc4Y2I0YTQ2NGQ1Yg==; Hm_lvt_3f5a4376e51b71a2dd87a5f1f1d75847=1718611945; __cas__rn__=468624134; __cas__st__3=892dc7537e692154f4e0b9fe37e78a4a7a7d90a150fad0c5688ac5b055d9bb354f81c50df5d357ab3acf0d40; __cas__id__3=50763856; CPTK_3=1707430383; CPID_3=50763856; Hm_lvt_863779a7a3a15a5b2bff4338a01f002e=1718611946; Hm_up_863779a7a3a15a5b2bff4338a01f002e=%7B%22uid_%22%3A%7B%22value%22%3A%2250763856%22%2C%22scope%22%3A1%7D%2C%22optid%22%3A%7B%22value%22%3A%2250763856%22%2C%22scope%22%3A1%7D%7D; Hm_lpvt_3f5a4376e51b71a2dd87a5f1f1d75847=1718611999; Hm_lpvt_863779a7a3a15a5b2bff4338a01f002e=1718611999; RT="z=1&dm=baidu.com&si=c0c89987-96b5-432c-a0be-d947ffd27e37&ss=lxi9kyqz&sl=2q&tt=1fne&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=fnlbq"';
        $url = 'https://fengchao.baidu.com/hairuo/request.ajax?path=lightning%2FGET%2FKeywordSuggestService%2FgetKeywordRecommendPassive&reqid='.$reqid;
        $data = [
            'reqid' => $reqid,
            'userid' => $user_id,
            'token' => $token,
            'path' => ' lightning%2FGET%2FKeywordSuggestService%2FgetKeywordRecommendPassive',
            'params' => '{"keyWordRecommendFilter":{"device":0,"positiveWords":[],"negativeWords":[],"fieldFilters":[],"keywordRecommendReasons":[],"searchRegions":"9999999","regionExtend":false,"removeDuplicate":false,"removeCampaignDuplicate":false},"source":"web","queryBy":0,"pageNo":1,"pageSize":3000,"wordQuerys":["'.$keyword.'"],"querySessions":["'.$keyword.'"],"entryMessage":"kr_station"}'
        ];
        $array = [
            'Accept:application/json',
            'Content-Type:application/x-www-form-urlencoded',
            'Cache-Contro:no-cache',
            'Cookie:'.$cookie
        ];
        $res = $this->curl($url,$array,true,$data);
        $res = json_decode($res);
        if(empty($res))return [];
        if(empty($res->data))return [];
        if(empty($res->data->keywordRecommendItems))return [];
        $keyword = $res->data->keywordRecommendItems[0];
        $data = [];
        $data['all'] = $keyword->averageMonthPv;
        $data['guiding_price'] = $keyword->recommendPrice;
        $data['click'] = $keyword->click;
        $data['data'] = $keyword;
        $data['competition'] = $keyword->competition;
        $data['show_reasons'] = implode(',',$keyword->showReasons);
        $a = $b = [];
        $count = 0;
        $i = 1;
        while($count < 20){
            if (empty($res->data->keywordRecommendItems[$i]))break;
            $keyword = $res->data->keywordRecommendItems[$i];
            $i++;
            if(strpos($keyword->keyword,$string))continue;
            $item = [
                'keyword' => $keyword->keyword,
                'showReasons' => implode(',',$keyword->showReasons)
            ];
            if (!empty($keyword->showReasons))
                $a[] = $item;
            else
                $b[] = $item;
            $count++;
        }
        if (!empty($a) || !empty($b))
            $data['keywords'] = array_merge($a,$b);
        // dd($res->data->keywordRecommen   dItems[0]);
        return $data;
    }

    /**
     * 爬取百度指数数据
     * @param string $keyword
     * @param string $cookie
     * @return mixed
     */
    public function baidu(string $keyword, string $cookie,string $cipherText){
        $value = [
            [
                ["name" => $keyword,"wordType" => 1]
            ]
        ];
        $value = json_encode($value,JSON_UNESCAPED_SLASHES);
        $last_time = \app\model\Config::get_value('last_time');
        if($last_time == 1){
            $datetime = $this->last_month();
        }elseif($last_time == 2){
            $datetime = $this->last_three_month();
        }else{
            $datetime = $this->last_year();
        }
        $url = 'https://index.baidu.com/api/SearchApi/index?area=0&word='.$value.'&startDate='.$datetime.'&endDate='.date('Y-m-d');
        $array = [
            'Content-Type:application/json',
            'Cipher-Text:'.$cipherText,
            'Cookie:'.$cookie
        ];
        //百度指数数据查询
        // dd($array);
        $res = $this->curl($url,$array,false);
        $res = json_decode($res);
        if (empty($res->data->generalRatio))
            $data['number'] = (object)[
                'all' => (object)['avg' => 0],
                'pc' => (object)['avg' => 0],
                'wise' => (object)['avg' => 0],
            ];
        else
            $data['number'] = $res->data->generalRatio[0];
        //百度相关词条查询
//        $url = 'https://index.baidu.com/api/WordGraph/multi?wordlist[]='.$keyword;
//        $res = $this->curl($url,$array);
//        $res = json_decode($res);
//        $data['wordlist'] = $res->data->wordlist[0]->wordGraph;
        return $data;
    }

    public function zhanzhanggongju(string $keyword, string $cookie)
    {
        $url = 'https://rank.chinaz.com/ajaxsync.aspx?at=index';
        $html = $this->curl($url, [
            'user-agent:ApiPOST Runtime +https://www.apipost.cn',
            'Cookie:' . $cookie,
            'origin:https://rank.chinaz.com',
            'accept-encoding:gzip, deflate, br',
            'Referer:https://rank.chinaz.com/wordsindex.aspx',
            'Content-Type:application/x-www-form-urlencoded; charset=UTF-8'
        ], true, ['kw' => urlencode($keyword)]);
        $pattern = '/mindex:\'(.*?)\'/';
        preg_match_all($pattern, $html, $mindex);
        $pattern = '/pcindex:\'(.*?)\'/';
        preg_match_all($pattern, $html, $pcindex);
        while (empty($mindex[1])){
            $html = $this->curl($url, [
                'user-agent:ApiPOST Runtime +https://www.apipost.cn',
                'Cookie:' . $cookie,
                'origin:https://rank.chinaz.com',
                'accept-encoding:gzip, deflate, br',
                'Referer:https://rank.chinaz.com/wordsindex.aspx',
                'Content-Type:application/x-www-form-urlencoded; charset=UTF-8'
            ], true, ['kw' => urlencode($keyword)]);
            preg_match_all($pattern, $html, $mindex);
            preg_match_all($pattern, $html, $pcindex);
            sleep(1);
        }
        !empty($mindex[1]) && $this->phone = $mindex[1][0];
        !empty($pcindex[1]) && $this->computer = $pcindex[1][0];
        return ['pc' => $this->computer,'phone' => $this->phone,'keyword' => []];
//        $url = 'https://data.chinaz.com/keyword/allindex/' . urlencode($keyword) .'/m-0';
//        $array = [
//            'Cookie:' . $cookie
//        ];
//        $html = $this->curl($url, $array, false);
//        if (strpos($html,'抱歉，未找到相关的数据。') !== false) return [];
//        // 使用正则表达式提取中间内容
//        $pattern = '/<li class="col-220 z-tl nofoldtxt">(.*?)<\/li>/';
//        $type = 1;
//        preg_match_all($pattern, $html, $matches);
//        if (empty($matches[1])){
//            $type = 2;
//            $pattern = '/<li class="w60 blue2 arow" style="overflow: hidden">(.*?)<\/li>/';
//            preg_match_all($pattern, $html, $matches);
//        }
//        // 提取到的中间内容存储在$matches中
//        if (!empty($matches[1])) {
//            $html = implode(',',$matches[1]);
//            $html = str_replace(['*','%','#','!','@','^','&','(',')'],'',$html);
//            if($type == 1){
//                $pattern = '/title="(.*?)"/';
//                preg_match_all($pattern, $html, $matches);
//                return ['pc' => $this->computer,'phone' => $this->phone,'keyword' => $matches[1]];
//            }else{
//                $html = str_replace(['<span style=\'color:red\'>','</span>'],['',''],$html);
//                // dd(explode(',',$html));
//                return ['pc' => $this->computer,'phone' => $this->phone,'keyword' => explode(',',$html)];
//            }
//        }else{
//            return [];
//        }
    }

    public function baiduc_(){
        $url = 'https://fengchao.baidu.com/hairuo/request.ajax?path=lightning%2FGET%2FKeywordSuggestService%2FgetKeywordRecommendPassive&reqid=4b534c48-c74d-4c35-fe9f-170848304240';
    }

    /**
     * curl POST
     * @param $url
     * @param $header
     * @return mixed
     */
    public function curl($url, $header,$is_post = true,$data = []){
        // $useragent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36';
        // 创建一个cURL资源
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, $is_post);
        curl_setopt($ch, CURLOPT_URL, $url);          // 设置目标网页的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将返回的内容作为字符串返回，而不是直接输出
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//禁止 cURL 验证对等证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//是否检测服务器的域名与证书上的是否一致
        curl_setopt($ch, CURLOPT_ENCODING, "" );
        curl_setopt($ch, CURLOPT_AUTOREFERER, true );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10 );
        curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
        if(!empty($data)){
            $post = http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        // curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
        // 执行cURL请求
        $response = curl_exec($ch);
        // 关闭cURL资源
        curl_close($ch);
        // 检查是否有错误发生
        if ($response === false) {
            $error = curl_error($ch);
            return '403';
//            die(json(['data' => [],'code' => 400,'msg' => '无法查询到数据']));
        } else {
            // 处理返回的内容
            return $response;
        }
    }

    /**
     * 取得上一个月的时间
     * @return string
     */
    public function last_month() : string{
        $currentDate = date('Y-m-d'); // 获取当前日期
        $lastMonth = date('Y-m-d', strtotime('-1 month', strtotime($currentDate))); // 获取上个月日期
        return (string)$lastMonth;
    }


    /**
     * 取得上三个月的时间
     * @return string
     */
    public function last_three_month() : string{
        $currentDate = date('Y-m-d'); // 获取当前日期
        $lastMonth = date('Y-m-d', strtotime('-3 month', strtotime($currentDate))); // 获取上个月日期
        return (string)$lastMonth;
    }

    /**
     * 取得前一年的时间
     * @return string
     */
    public function last_year() : string {
        $currentDate = date('Y-m-d'); // 获取当前日期
        $lastMonth = date('Y-m-d', strtotime('-1 year', strtotime($currentDate))); // 获取上个月日期
        return (string)$lastMonth;
    }

    /**
     * 解决汉字一个占三个字符串的问题
     * @param $string
     * @return int
     */
    public function length($string) : int{
        $pattern = '/[\x{4e00}-\x{9fa5}]/u'; // 匹配汉字的正则表达式
        preg_match_all($pattern, $string, $matches);
        $chineseChars = $matches[0];
        $number = count($chineseChars);
        return floor(strlen($string) - $number * 2);
    }
}